<?php
class Product extends Admin_Controller{
	var $default_path;
	var $main_path;
	var $small_path;
 	var $medium_path;
  	var $big_path;
  	var $medium_width;
  	var $medium_height;
  	var $big_width;
  	var $big_height;
	public function __construct(){
		parent::__construct();
		$this->load->Model(array("Mcatalogue_product","Mproduct"));
		$this->default_path = './assets/filemanager/default.jpg';
		$this->main_path = './assets/filemanager/product/';
		$this->medium_width = '170';
	  	$this->medium_height = '170';
	  	$this->big_width = '400';
	  	$this->big_height = '400';
	}
	public function index(){
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_product'),base_url().'admincp/product');
		
		if($this->input->is_ajax_request()){
            $output = $this->Mproduct->listProduct();
            $this->output->set_output(json_encode($output));
        }else{
            $data['template']="product/view";
            $data['title_page']='<i class="icon20 icon20 i-list"></i> Product Manager';
			$this->load->view("admincp/template",$data);
        }
	}

	public function add(){
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_product'),base_url().'admincp/product');
		$this->breadcrumb->append_crumb(trans('breadcrumb_product_add'),base_url().'admincp/product/add');
		$data['template']="product/add";
		$data['title_page']='<i class="icon20 i-plus-circle-2"></i> '.trans('title_product_add');
		$data['catalogue_product']=$this->Mcatalogue_product->list_all();

		if($this->input->post("ok") != ""){
			$this->form_validation->set_rules("cata_id","catalogue product","is_natural_no_zero");
			$this->form_validation->set_rules("pro_title","product title","required");
			
			if($this->form_validation->run() == FALSE){ 
				$error = validation_errors();
				$error = explode("\n",$error);
				foreach($error as $err){
					if($err != ""){
           				$data['error'][] = $err;
					}
				}
			}else{
				$cata_id = $this->input->post('catalogue_product');
				$dataImage['default_image'] = $this->default_path;
				if(isset($_FILES['pro_img'])){
					$path_upload = $this->main_path.$cata_id.'/';
					$this->small_path = $path_upload.'small/';
			   	 	$this->medium_path = $path_upload.'medium/';
			    	$this->big_path = $path_upload.'big/';
			    	if (!is_dir($path_upload)) {
			            mkdir($path_upload);
			        }
					$config['upload_path'] = $path_upload;
					$config['allowed_types'] = 'gif|jpg|png';
					$config['encrypt_name'] = TRUE;
					$config['quality'] = '100%';
					$this->load->library('upload', $config);
					
			        if (!$this->upload->do_upload('pro_img')){
			        	$data['error'][] = $this->upload->display_errors();
					}else{
						$img = $this->upload->data();
						if(!empty($img)){
							$image = $img['file_name'];

							$this->load->library('image_lib');
							$config['image_library'] = 'gd2';
							$config['source_image']	= $path_upload.$image;

							if (!is_dir($this->medium_path)) {
					            mkdir($this->medium_path);
					        }
							$config['new_image']	= $this->medium_path.$image;
							$config['width']	 = $this->medium_width;
							$config['height']	= $this->medium_height;
							$this->image_lib->initialize($config);
							$this->image_lib->resize();

							if (!is_dir($this->big_path)) {
					            mkdir($this->big_path);
					        }
							$config['new_image']	= $this->big_path.$image;
							$config['width']	 = $this->big_width;
							$config['height']	= $this->big_height;
							$this->image_lib->initialize($config);
							$this->image_lib->resize();

							unlink($path_upload.$image);

							$dataImage['medium_image'] = $this->medium_path.$image;
							$dataImage['big_image'] = $this->big_path.$image;
						}
					}
				}

				$pro_title = $this->input->post('pro_title');
				$dataInsert = array(
					'pro_title' => $pro_title,
					'pro_image' => serialize($dataImage),
					'cata_id' => $cata_id,
					'date_add' => date('Y-m-d',time()), 
				);
				$this->Mproduct->insert($dataInsert);
				$this->cache->delete_group('product_');
				$this->cache->delete('home');
				$this->session->set_flashdata(array("success"=>trans('message_create_successfully')));
				redirect(base_url()."admincp/product");
			}
		}
		$this->load->view("admincp/template",$data);
	}

	public function edit(){
		$id = $this->uri->segment(5);
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_product'),base_url().'admincp/product');
		$this->breadcrumb->append_crumb(trans('breadcrumb_product_edit'),base_url().'admincp/product/edit/id/'.$id);
		$data['template']="product/edit";
		$data['title_page']='<i class="icon20 i-pen-2"></i> '.trans('title_product_edit');
		$data['catalogue_product']=$this->Mcatalogue_product->list_all();
		$data['info']=$this->Mproduct->get_data($id);
		
		if($this->input->post("ok") != ""){
			$this->form_validation->set_rules("cata_id","catalogue product","is_natural_no_zero");
			$this->form_validation->set_rules("pro_title","product title","required");
			
			if($this->form_validation->run() == FALSE){ 
				$error = validation_errors();
				$error = explode("\n",$error);
				foreach($error as $err){
					if($err != ""){
           				$data['error'][] = $err;
					}
				}
			}else{
				$cata_id = $this->input->post('catalogue_product');
				$dataImage = @unserialize($data['info']['image']);
				if ($dataImage === false && $string !== 'b:0;') {
				    $dataImage['default_image'] = $this->default_path;
				}
				
				if(isset($_FILES['pro_img'])){
					$path_upload = $this->main_path.$cata_id.'/';
					$this->small_path = $path_upload.'small/';
			   	 	$this->medium_path = $path_upload.'medium/';
			    	$this->big_path = $path_upload.'big/';
			    	if (!is_dir($path_upload)) {
			            mkdir($path_upload);
			        }
					$config['upload_path'] = $path_upload;
					$config['allowed_types'] = 'gif|jpg|png';
					$config['encrypt_name'] = TRUE;
					$config['quality'] = '100%';
					$this->load->library('upload', $config);
					
			        if (!$this->upload->do_upload('pro_img')){
			        	$data['error'][] = $this->upload->display_errors();
					}else{
						$img = $this->upload->data();
						if(!empty($img)){
							$image = $img['file_name'];
							foreach($dataImage as $ketDI => $itemDI){
								if($ketDI != 'default_image'){
									unlink($itemDI);
								}
							}
							$this->load->library('image_lib');
							$config['image_library'] = 'gd2';
							$config['source_image']	= $path_upload.$image;

							if (!is_dir($this->medium_path)) {
					            mkdir($this->medium_path);
					        }
							$config['new_image']	= $this->medium_path.$image;
							$config['width']	 = $this->medium_width;
							$config['height']	= $this->medium_height;
							$this->image_lib->initialize($config);
							$this->image_lib->resize();

							if (!is_dir($this->big_path)) {
					            mkdir($this->big_path);
					        }
							$config['new_image']	= $this->big_path.$image;
							$config['width']	 = $this->big_width;
							$config['height']	= $this->big_height;
							$this->image_lib->initialize($config);
							$this->image_lib->resize();

							unlink($path_upload.$image);

							$dataImage['medium_image'] = $this->medium_path.$image;
							$dataImage['big_image'] = $this->big_path.$image;
						}
					}
				}
				$pro_title = $this->input->post('pro_title');
				$dataUpdate = array(
					'pro_title' => $pro_title,
					'pro_image' => serialize($dataImage),
					'cata_id' => $this->input->post('catalogue_product'),
					'date_edit' => date('Y-m-d',time()), 
				);
				$this->Mproduct->update($dataUpdate,$id);
				$this->cache->delete_group('product_');
				$this->cache->delete('home');
				$this->session->set_flashdata(array("success"=>trans('message_edit_successfully')));
				redirect(base_url()."admincp/product");
			}
		}
		$this->load->view("admincp/template",$data);
	}

	public function delete(){
		$id = $this->uri->segment(5);
		$info=$this->Mproduct->get_data($id);
		$dataImage = unserialize($info['image']);
		foreach($dataImage as $ketDI => $itemDI){
			if($ketDI != 'default_image'){
				unlink($itemDI);
			}
		}
		$this->Mproduct->delete($id);
		$this->session->set_flashdata(array("success"=>trans('message_delete_successfully')));
		redirect(base_url()."admincp/product");
	}
	
	public function process(){
		if($this->input->is_ajax_request()){
			$id = $this->input->post("cata_id");
			$pro_id = $this->input->post("pro_id");
			$data = $this->Mproduct->list_all_by_cata_id($id);
			$html = '';
			foreach ($data as $value) {
				if($pro_id == $value['pro_id']){
					$html .= '<option value="'.$value['pro_id'].'" selected="selected">'.$value['pro_title'].'</option>';
				}else{
					$html .= '<option value="'.$value['pro_id'].'">'.$value['pro_title'].'</option>';
				}
			}
			$respone['html'] = $html;
			echo json_encode($respone);
		}
	}
}